package com.longxi.tianjintianbao.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by cxw on & 2018/12/13
 */
public class AESUtil {

    final static int h2b_A_10 = 'A' - 10;
    final static int h2b_a_10 = 'a' - 10;
    static void byteToHex(char[] hex, int index, byte b) {
        int h = b >>> 4 & 0xF;
        hex[index] = (char) (h > 9 ? h + h2b_a_10 : h + '0');
        h = b & 0xF;
        hex[index + 1] = (char) (h > 9 ? h + h2b_a_10 : h + '0');
    }

    static void byteToHexUpper(char[] hex, int index, byte b) {
        int h = b >>> 4 & 0xF;
        hex[index] = (char) (h > 9 ? h + h2b_A_10 : h + '0');
        h = b & 0xF;
        hex[index + 1] = (char) (h > 9 ? h + h2b_A_10 : h + '0');
    }

    public static String bytesToHex(byte[] bytes, boolean withPrefix,
                                    boolean upperCase) {
        if (bytes == null) {
            throw new NullPointerException();
        }
        if (bytes.length == 0) {
            if (withPrefix) {
                return "0x";
            } else {
                return "";
            }
        }
        char[] hex = new char[bytes.length * 2 + (withPrefix ? 2 : 0)];
        int j = 0;
        if (withPrefix) {
            hex[j++] = '0';
            hex[j++] = 'x';
        }
        if (upperCase) {
            for (byte b : bytes) {
                byteToHexUpper(hex, j, b);
                j += 2;
            }
        } else {
            for (byte b : bytes) {
                byteToHex(hex, j, b);
                j += 2;
            }
        }
        return new String(hex);
    }

    public static String encrypt(String data, String key) throws Exception {
        byte[] result = encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8" + ""));
        return bytesToHex(result, false, false);
    }

    public static byte[] encrypt(byte[] content, byte[] key) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] result = cipher.doFinal(content);
        return result;
    }

}
